#!/bin/bash
set -e

# version check: https://github.com/jemalloc/jemalloc/releases

# Newer aarch64 platforms, like Raspberry Pi 5 with Debian Bookworm, are
# shipping with PAGESIZE=16K. Setting it here is retrocompatible with older
# systems, so it's safe to set it unconditionally for arm.
# This means aarch64 will use the latest jemalloc, where we can configure the
# page size, while x64 will keep using our pinned 3.6.0 jemalloc
if uname -m | grep -qi 'aarch64'; then
  mkdir /jemalloc-new
  cd /jemalloc-new

  wget -q https://github.com/jemalloc/jemalloc/releases/download/5.3.0/jemalloc-5.3.0.tar.bz2
  sha256sum jemalloc-5.3.0.tar.bz2
  echo "2db82d1e7119df3e71b7640219b6dfe84789bc0537983c3b7ac4f7189aecfeaa jemalloc-5.3.0.tar.bz2" | sha256sum -c
  tar --strip-components=1 -xjf jemalloc-5.3.0.tar.bz2
  ./configure --prefix=/usr --with-lg-page=16 && make build_lib -j"$(nproc)" && make install_lib_shared
  cd / && rm -rf /jemalloc-new
else
  # jemalloc stable
  mkdir /jemalloc-stable
  cd /jemalloc-stable

  wget -q https://github.com/jemalloc/jemalloc/releases/download/3.6.0/jemalloc-3.6.0.tar.bz2
  sha256sum jemalloc-3.6.0.tar.bz2
  echo "e16c2159dd3c81ca2dc3b5c9ef0d43e1f2f45b04548f42db12e7c12d7bdf84fe jemalloc-3.6.0.tar.bz2" | sha256sum -c
  tar --strip-components=1 -xjf jemalloc-3.6.0.tar.bz2
  ./configure --prefix=/usr $EXTRA_CONF && make -j"$(nproc)" && make install_lib_shared
  cd / && rm -rf /jemalloc-stable

  # jemalloc new
  mkdir /jemalloc-new
  cd /jemalloc-new

  wget -q https://github.com/jemalloc/jemalloc/releases/download/5.3.0/jemalloc-5.3.0.tar.bz2
  sha256sum jemalloc-5.3.0.tar.bz2
  echo "2db82d1e7119df3e71b7640219b6dfe84789bc0537983c3b7ac4f7189aecfeaa jemalloc-5.3.0.tar.bz2" | sha256sum -c
  tar --strip-components=1 -xjf jemalloc-5.3.0.tar.bz2
  ./configure --prefix=/usr --with-install-suffix=5.3.0 && make build_lib -j"$(nproc)" && make install_lib_shared
  cd / && rm -rf /jemalloc-new
fi
